﻿namespace Snake.App
{
	using System;
	using System.Collections.Generic;
	using Entities;

	public class ActionRouter
	{
		private Dictionary<ActionsKey, Action> actionsTable;
		private RotateDirection rotateAction;

		public ActionRouter()
		{
			actionsTable = new Dictionary<ActionsKey, Action>
			               	{
			               		{ActionsKey.Right, RightKey},
			               		{ActionsKey.Left, LeftKey},
			               		{ActionsKey.Up, UpKey},
			               		{ActionsKey.Down, DownKey},
			               	};
		}

		internal RotateDirection RouteAction(ActionsKey nextAction, SnakeDirection snakeDirection)
		{
			rotateAction = RotateDirection.None;
			Action action;
			actionsTable.TryGetValue(nextAction, out action);
			if (action != null)	
				action(snakeDirection);

			return rotateAction;
		}


		private void DownKey(SnakeDirection snakeDirection)
		{
			if (snakeDirection == SnakeDirection.Left)
				rotateAction = RotateDirection.CounterClockwise;
			if (snakeDirection == SnakeDirection.Right)
				rotateAction = RotateDirection.Clockwise;
		}

		private void UpKey(SnakeDirection snakeDirection)
		{
			if (snakeDirection == SnakeDirection.Right)
				rotateAction = RotateDirection.CounterClockwise;
			if (snakeDirection == SnakeDirection.Left)
				rotateAction = RotateDirection.Clockwise;
		}

		private void LeftKey(SnakeDirection snakeDirection)
		{
			if (snakeDirection == SnakeDirection.Up)
				rotateAction = RotateDirection.CounterClockwise;
			if (snakeDirection == SnakeDirection.Down)
				rotateAction = RotateDirection.Clockwise;
		}

		private void RightKey(SnakeDirection snakeDirection)
		{
			if (snakeDirection == SnakeDirection.Down)
				rotateAction = RotateDirection.CounterClockwise;
			if (snakeDirection == SnakeDirection.Up)
				rotateAction = RotateDirection.Clockwise;
		}

		private delegate void Action(SnakeDirection snakeDirection);
	}
}